package com.onlineshop.controller.admin;

import com.onlineshop.dao.ProductDao;
import com.onlineshop.entity.Product;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/products")
public class ProductListServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 6; // 每页显示数量

        String pageParam = request.getParameter("page");
        if (pageParam != null && !pageParam.trim().isEmpty()) {
            try {
                page = Integer.parseInt(pageParam);
            } catch (NumberFormatException e) {
                // 保持默认值
            }
        }

        int totalCount = productDao.getProductCount();
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        List<Product> products = productDao.getProductsByPage(page, pageSize);

        request.setAttribute("products", products);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("/admin/product_list.jsp").forward(request, response);
    }
}